package com.engine4cloud.tdf.common.core.util.graph;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class PointInPolygon {
    public static boolean isPointInPolygon(Point point, Polygon polygon) {
        boolean inside = false;

        int n = polygon.getVertices().size();

        for (int i = 0, j = n - 1; i < n; j = i++) {
            Point pi = polygon.getVertices().get(i);
            Point pj = polygon.getVertices().get(j);

            if (isIntersect(point, pi, pj)) {
                inside = !inside;
            }
        }

        return inside;
    }

    private static boolean isIntersect(Point point, Point pi, Point pj) {
        BigDecimal xi = pi.getX(), yi = pi.getY();
        BigDecimal xj = pj.getX(), yj = pj.getY();
        BigDecimal px = point.getX(), py = point.getY();

        return ((yi.compareTo(py) > 0) != (yj.compareTo(py) > 0)) &&
                (px.compareTo(xi.add(xj.subtract(xi).multiply(py.subtract(yi)).divide(yj.subtract(yi), 10, RoundingMode.HALF_UP))) < 0);
    }
}
